<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>二分查找 | SunMoon Space</title><meta name="keywords" content="Fly"><meta name="author" content="Sun Moon"><meta name="copyright" content="Sun Moon"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="二分查找一文带你搞定二分搜索及多个变种 - 搜索旋转排序数组 II - 力扣（LeetCode） (leetcode-cn.com) 1. 有序数组在有序集合查找target过程 时间复杂度：logn 2要素：  Target目标值 查找区间（left，rigth索引）  模板1结束的时候，右指针在左，左指针在右，没找到结果时，右指针最接近target。 int binarySearch(int[">
<meta property="og:type" content="article">
<meta property="og:title" content="二分查找">
<meta property="og:url" content="https://www.sunmoon.site/2020/01/29/%E7%AE%97%E6%B3%95/%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE/index.html">
<meta property="og:site_name" content="SunMoon Space">
<meta property="og:description" content="二分查找一文带你搞定二分搜索及多个变种 - 搜索旋转排序数组 II - 力扣（LeetCode） (leetcode-cn.com) 1. 有序数组在有序集合查找target过程 时间复杂度：logn 2要素：  Target目标值 查找区间（left，rigth索引）  模板1结束的时候，右指针在左，左指针在右，没找到结果时，右指针最接近target。 int binarySearch(int[">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://s1.ax1x.com/2022/05/19/OHACxx.md.jpg">
<meta property="article:published_time" content="2020-01-28T16:37:00.000Z">
<meta property="article:modified_time" content="2022-08-30T15:08:11.148Z">
<meta property="article:author" content="Sun Moon">
<meta property="article:tag" content="Fly">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://s1.ax1x.com/2022/05/19/OHACxx.md.jpg"><link rel="shortcut icon" href="/img/avatar.jpg"><link rel="canonical" href="https://www.sunmoon.site/2020/01/29/%E7%AE%97%E6%B3%95/%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: Sun Moon","link":"链接: ","source":"来源: SunMoon Space","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '二分查找',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-08-30 23:08:11'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/css/backgound.css"><meta name="generator" content="Hexo 5.4.2"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/archives/"><div class="headline">文章</div><div class="length-num">43</div></a></div><div class="data-item"><a href="/tags/"><div class="headline">标签</div><div class="length-num">25</div></a></div><div class="data-item"><a href="/categories/"><div class="headline">分类</div><div class="length-num">10</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> Archives</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 链接</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></li><li><a class="site-page child" href="/about/"><i class="fa-fw fas fa-heart"></i><span> About</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/aplayer/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://s1.ax1x.com/2022/05/19/OHACxx.md.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">SunMoon Space</a></span><div id="he-plugin-simple"></div><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> Archives</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 链接</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></li><li><a class="site-page child" href="/about/"><i class="fa-fw fas fa-heart"></i><span> About</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/aplayer/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">二分查找</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-01-28T16:37:00.000Z" title="发表于 2020-01-29 00:37:00">2020-01-29</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-08-30T15:08:11.148Z" title="更新于 2022-08-30 23:08:11">2022-08-30</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E7%AE%97%E6%B3%95/">算法</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="二分查找"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="二分查找"><a href="#二分查找" class="headerlink" title="二分查找"></a>二分查找</h1><p><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/search-in-rotated-sorted-array-ii/solution/yi-wen-dai-ni-gao-ding-er-fen-sou-suo-ji-ki52/">一文带你搞定二分搜索及多个变种 - 搜索旋转排序数组 II - 力扣（LeetCode） (leetcode-cn.com)</a></p>
<h2 id="1-有序数组"><a href="#1-有序数组" class="headerlink" title="1. 有序数组"></a>1. 有序数组</h2><p>在有序集合查找target过程</p>
<p>时间复杂度：logn</p>
<p>2要素：</p>
<ul>
<li>Target目标值</li>
<li>查找区间（left，rigth索引）</li>
</ul>
<h3 id="模板1"><a href="#模板1" class="headerlink" title="模板1"></a>模板1</h3><p>结束的时候，右指针在左，左指针在右，没找到结果时，右指针最接近target。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">int binarySearch(int[] nums, int target)&#123;</span><br><span class="line">  if(nums == null || nums.length == 0)</span><br><span class="line">    return -1;</span><br><span class="line"></span><br><span class="line">  int left = 0, right = nums.length - 1;</span><br><span class="line">  while(left &lt;= right)&#123;</span><br><span class="line">    int mid = left + (right - left) / 2;    //这种方式可以防止整数溢出</span><br><span class="line">    if(nums[mid] == target)&#123; return mid; &#125;</span><br><span class="line">    else if(nums[mid] &lt; target) &#123; left = mid + 1; &#125;</span><br><span class="line">    else &#123; right = mid - 1; &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  // End Condition: left &gt; right</span><br><span class="line">  return -1;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="模板2"><a href="#模板2" class="headerlink" title="模板2"></a>模板2</h3><p><strong>结束时，左右指针在同一位置，若一定有target，返回一个指针即可。</strong><br><strong>若无target时，最后二者一定指向——大数，三种情况：target&lt;min,指向min；  target&gt;max, 指向max,其他指向target左右较大的</strong><br>（条件判断时只能用 if(nums[mid] &lt; target)  left &#x3D; mid + 1; else  right &#x3D; mid ;</p>
<p>不能用if(nums[mid] &lt;&#x3D; target)  left &#x3D; mid ; else  right &#x3D; mid-1 ;</p>
<p>否则会出现while无线循环，因为取mid时用的是两个数中偏小，若最后剩下两个数10，12，l，r分别指向10和12，目标值为11，mid始终指向10，left始终指向10，始终不会等于right，无法退出循环）</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">int binarySearch(int[] nums, int target)&#123;</span><br><span class="line">  if(nums == null || nums.length == 0)</span><br><span class="line">    return -1;</span><br><span class="line"></span><br><span class="line">  int left = 0, right = nums.length - 1;</span><br><span class="line">  while(left &lt; right)&#123;</span><br><span class="line">    int mid = left + (right - left) / 2;    //这种方式可以防止整数溢出</span><br><span class="line">    if(nums[mid] &lt; target)  left = mid + 1; </span><br><span class="line">    else  right = mid ; </span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  // End Condition: left = right</span><br><span class="line">  return left;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="例题"><a href="#例题" class="headerlink" title="例题"></a>例题</h3><p><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/sqrtx/">69. x 的平方根 - 力扣（LeetCode） (leetcode-cn.com)</a></p>
<ul>
<li>在1-x的区间上找到一个数mid，使得x&#x2F;mid &#x3D;&#x3D; mid即可；以二分查找的方式  找mid</li>
<li><strong>重点：二分查找的特点，若没有找到target，right指针一定指向最接近target</strong></li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">public int mySqrt(int x) &#123;</span><br><span class="line">        if(x == 0 || x == 1)&#123;</span><br><span class="line">            return x;</span><br><span class="line">        &#125;</span><br><span class="line">        int left = 1;</span><br><span class="line">        int right = x;</span><br><span class="line">        while(left &lt;= right)&#123;</span><br><span class="line">            int mid = (left + right)/2;</span><br><span class="line">            if(mid == x / mid)&#123;</span><br><span class="line">                return mid;</span><br><span class="line">            &#125;else if(mid &gt; x / mid)&#123; //说明mid偏大，target在左边</span><br><span class="line">                right = mid - 1;</span><br><span class="line">            &#125;else&#123;</span><br><span class="line">                left = mid + 1;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        //没有找到合适的mid，一定是ringt指向的数子</span><br><span class="line">        return right;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/search-in-rotated-sorted-array/">33. 搜索旋转排序数组 - 力扣（LeetCode） (leetcode-cn.com)</a></p>
<p>通过比较target和nums[0],确定目标在左半部分还是右半部分。</p>
<p>例如 target &#x3D; 5, 目标值在左半段，因此在 [4, 5, 6, 7, inf, inf, inf] 这个有序数组里找就行了；<br>例如 target &#x3D; 1, 目标值在右半段，因此在 [-inf, -inf, -inf, -inf, 0, 1, 2] 这个有序数组里找就行了。<br>如此，我们又双叒叕将「旋转数组中找目标值」 转化成了 「有序数组中找目标值」</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">search</span><span class="params">(<span class="type">int</span>[] nums, <span class="type">int</span> target)</span> &#123;</span><br><span class="line">        <span class="type">int</span> <span class="variable">n</span> <span class="operator">=</span> nums.length;</span><br><span class="line">        <span class="keyword">if</span>(n == <span class="number">1</span>)&#123;</span><br><span class="line">            <span class="keyword">return</span> nums[<span class="number">0</span>] == target?<span class="number">0</span>:-<span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="type">int</span> l=<span class="number">0</span>;</span><br><span class="line">        <span class="type">int</span> <span class="variable">r</span> <span class="operator">=</span> n-<span class="number">1</span>;</span><br><span class="line">        <span class="keyword">while</span>(l &lt;= r)&#123;</span><br><span class="line">            <span class="type">int</span> <span class="variable">mid</span> <span class="operator">=</span> l + (r - l)/<span class="number">2</span>;</span><br><span class="line">            <span class="keyword">if</span>(nums[mid] == target)&#123;</span><br><span class="line">                <span class="keyword">return</span> mid;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span>(nums[<span class="number">0</span>] &lt;= target)&#123;</span><br><span class="line">                <span class="comment">//在左段</span></span><br><span class="line">                <span class="comment">//若mid指向右半段，将其设置为inf</span></span><br><span class="line">                <span class="keyword">if</span>(nums[mid] &lt; nums[<span class="number">0</span>])&#123;</span><br><span class="line">                    nums[mid] = Integer.MAX_VALUE;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                <span class="comment">//在右端</span></span><br><span class="line">                <span class="comment">//若mid指向左半段，将其设置为-inf</span></span><br><span class="line">                <span class="keyword">if</span>(nums[mid] &gt;= nums[<span class="number">0</span>])&#123;</span><br><span class="line">                    nums[mid] = Integer.MIN_VALUE;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span>(target &lt; nums[mid])&#123;</span><br><span class="line">                r = mid - <span class="number">1</span>;</span><br><span class="line">            &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                l = mid + <span class="number">1</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="2-部分有序数组"><a href="#2-部分有序数组" class="headerlink" title="2. 部分有序数组"></a>2. 部分有序数组</h2><p>将有序数组后半部分翻转到前面，相当于两个有序数组。<br>主要考虑nums[mid]落在数组1还是数组2。</p>
<h2 id="3-无序数组求峰值"><a href="#3-无序数组求峰值" class="headerlink" title="3. 无序数组求峰值"></a>3. 无序数组求峰值</h2><p>在一定存在峰值的情况下，且可假设 <code>nums[-1] = nums[n] = -∞</code>；</p>
<p>根据左右指针计算中间位置 m，并比较 m 与 m+1 的值，如果 m 较大，则左侧存在峰值，r &#x3D; m，如果 m + 1 较大，则右侧存在峰值，l &#x3D; m + 1</p>
<h3 id="例题-1"><a href="#例题-1" class="headerlink" title="例题"></a>例题</h3><p>核心思想：比较mid和mid+1位置，发生递增left右移动，发生递减right左移动。</p>
<ol>
<li>寻找峰值：<a target="_blank" rel="noopener" href="https://leetcode.cn/problems/find-peak-element/">162. 寻找峰值 - 力扣（LeetCode）</a></li>
</ol>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">findPeakElement</span><span class="params">(<span class="type">int</span>[] nums)</span> &#123;</span><br><span class="line">        <span class="type">int</span> <span class="variable">left</span> <span class="operator">=</span> <span class="number">0</span>, right = nums.length - <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">while</span> (left &lt; right ) &#123;</span><br><span class="line">            <span class="type">int</span> <span class="variable">mid</span> <span class="operator">=</span> left + (right - left) / <span class="number">2</span>;</span><br><span class="line">            <span class="keyword">if</span> (nums[mid] &gt; nums[mid + <span class="number">1</span>]) &#123;</span><br><span class="line">                right = mid;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                left = mid + <span class="number">1</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> left;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol start="2">
<li><a target="_blank" rel="noopener" href="https://leetcode.cn/problems/peak-index-in-a-mountain-array/">852. 山脉数组的峰顶索引 - 力扣（LeetCode）</a></li>
</ol>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">peakIndexInMountainArray</span><span class="params">(<span class="type">int</span>[] arr)</span> &#123;</span><br><span class="line">        <span class="type">int</span> <span class="variable">left</span> <span class="operator">=</span> <span class="number">0</span>, right = arr.length - <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">while</span> (left &lt; right ) &#123;</span><br><span class="line">            <span class="type">int</span> <span class="variable">mid</span> <span class="operator">=</span> left + (right - left) / <span class="number">2</span>;</span><br><span class="line">            <span class="keyword">if</span> (arr[mid] &gt; arr[mid + <span class="number">1</span>]) &#123;</span><br><span class="line">                right = mid;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                left = mid + <span class="number">1</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> right;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol start="3">
<li>搜索排序数组<a target="_blank" rel="noopener" href="https://leetcode.cn/problems/search-in-rotated-sorted-array/submissions/">33. 搜索旋转排序数组 - 力扣（LeetCode）</a></li>
<li><a target="_blank" rel="noopener" href="https://leetcode.cn/problems/find-minimum-in-rotated-sorted-array/">153. 寻找旋转排序数组中的最小值 - 力扣（LeetCode）</a><br><strong>思路：比较nums[mid]和nums[r]，nums[mid]&lt;nums[r]时在最小值一定在mid左边，nums[mid]&gt;&#x3D;nums[r]，mid一定在右边</strong></li>
</ol>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">findMin</span><span class="params">(<span class="type">int</span>[] nums)</span> &#123;</span><br><span class="line">        <span class="type">int</span> <span class="variable">low</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">        <span class="type">int</span> <span class="variable">high</span> <span class="operator">=</span> nums.length - <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">while</span> (low &lt; high) &#123;</span><br><span class="line">            <span class="type">int</span> <span class="variable">pivot</span> <span class="operator">=</span> low + (high - low) / <span class="number">2</span>;</span><br><span class="line">            <span class="keyword">if</span> (nums[pivot] &lt; nums[high]) &#123;</span><br><span class="line">                high = pivot;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                low = pivot + <span class="number">1</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> nums[low];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">Sun Moon</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://www.sunmoon.site/2020/01/29/%E7%AE%97%E6%B3%95/%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE/">https://www.sunmoon.site/2020/01/29/%E7%AE%97%E6%B3%95/%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://www.sunmoon.site" target="_blank">SunMoon Space</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="https://s1.ax1x.com/2022/05/19/OHACxx.md.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/wechat.jpg" target="_blank"><img class="post-qr-code-img" src="/img/wechat.jpg" alt="wechat"/></a><div class="post-qr-code-desc">wechat</div></li><li class="reward-item"><a href="/img/alipay.jpg" target="_blank"><img class="post-qr-code-img" src="/img/alipay.jpg" alt="alipay"/></a><div class="post-qr-code-desc">alipay</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2020/01/29/%E7%AE%97%E6%B3%95/%E4%BA%8C%E8%BF%9B%E5%88%B6%E4%BD%8D%E8%BF%90%E7%AE%97/"><img class="prev-cover" src="https://s1.ax1x.com/2022/05/19/OHApGR.md.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">位运算</div></div></a></div><div class="next-post pull-right"><a href="/2020/01/29/%E7%AE%97%E6%B3%95/%E6%95%B0%E7%BB%84%E8%AE%A1%E6%95%B0-%E6%8A%95%E7%A5%A8%E7%AE%97%E6%B3%95/"><img class="next-cover" src="https://s1.ax1x.com/2022/05/19/OHApGR.md.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">数组计数—投票算法</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Sun Moon</div><div class="author-info__description">Hi, welcome to my blog!</div></div><div class="card-info-data is-center"><div class="card-info-data-item"><a href="/archives/"><div class="headline">文章</div><div class="length-num">43</div></a></div><div class="card-info-data-item"><a href="/tags/"><div class="headline">标签</div><div class="length-num">25</div></a></div><div class="card-info-data-item"><a href="/categories/"><div class="headline">分类</div><div class="length-num">10</div></a></div></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/sun-moon22"><i class="fab fa-github"></i><span>关注我</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/sun-moon22" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="https://qm.qq.com/cgi-bin/qm/qr?k=zftgTJPReW-aEsUnWx6dKFfD03rovP8a&amp;noverify=0" target="_blank" title="QQ"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">欢迎来到我的博客！</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE"><span class="toc-number">1.</span> <span class="toc-text">二分查找</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-%E6%9C%89%E5%BA%8F%E6%95%B0%E7%BB%84"><span class="toc-number">1.1.</span> <span class="toc-text">1. 有序数组</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E6%9D%BF1"><span class="toc-number">1.1.1.</span> <span class="toc-text">模板1</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E6%9D%BF2"><span class="toc-number">1.1.2.</span> <span class="toc-text">模板2</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BE%8B%E9%A2%98"><span class="toc-number">1.1.3.</span> <span class="toc-text">例题</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-%E9%83%A8%E5%88%86%E6%9C%89%E5%BA%8F%E6%95%B0%E7%BB%84"><span class="toc-number">1.2.</span> <span class="toc-text">2. 部分有序数组</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-%E6%97%A0%E5%BA%8F%E6%95%B0%E7%BB%84%E6%B1%82%E5%B3%B0%E5%80%BC"><span class="toc-number">1.3.</span> <span class="toc-text">3. 无序数组求峰值</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BE%8B%E9%A2%98-1"><span class="toc-number">1.3.1.</span> <span class="toc-text">例题</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2022/05/02/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/%E5%89%8D%E7%BC%80%E6%95%B0/" title="前缀树"><img src="https://s1.ax1x.com/2022/05/19/OHApGR.md.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="前缀树"/></a><div class="content"><a class="title" href="/2022/05/02/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/%E5%89%8D%E7%BC%80%E6%95%B0/" title="前缀树">前缀树</a><time datetime="2022-05-01T16:37:00.000Z" title="发表于 2022-05-02 00:37:00">2022-05-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/04/30/%E4%BD%BF%E7%94%A8%E5%BF%85%E8%AF%BB/" title="Ikiler在线 Markdown"><img src="https://s1.ax1x.com/2022/05/19/OHAkqO.md.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Ikiler在线 Markdown"/></a><div class="content"><a class="title" href="/2022/04/30/%E4%BD%BF%E7%94%A8%E5%BF%85%E8%AF%BB/" title="Ikiler在线 Markdown">Ikiler在线 Markdown</a><time datetime="2022-04-29T16:37:00.000Z" title="发表于 2022-04-30 00:37:00">2022-04-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/04/29/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/%E5%B9%B3%E8%A1%A1%E4%BA%8C%E5%8F%89%E6%A0%91/" title="平衡二叉树"><img src="https://s1.ax1x.com/2022/05/19/OHA9R1.md.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="平衡二叉树"/></a><div class="content"><a class="title" href="/2022/04/29/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/%E5%B9%B3%E8%A1%A1%E4%BA%8C%E5%8F%89%E6%A0%91/" title="平衡二叉树">平衡二叉树</a><time datetime="2022-04-28T16:37:00.000Z" title="发表于 2022-04-29 00:37:00">2022-04-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/04/29/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/%E7%BA%BF%E6%80%A7%E8%A1%A8/" title="线性表"><img src="https://s1.ax1x.com/2022/05/19/OHApGR.md.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="线性表"/></a><div class="content"><a class="title" href="/2022/04/29/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/%E7%BA%BF%E6%80%A7%E8%A1%A8/" title="线性表">线性表</a><time datetime="2022-04-28T16:37:00.000Z" title="发表于 2022-04-29 00:37:00">2022-04-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/01/29/%E4%BA%92%E8%81%94%E7%BD%91%E7%94%9F%E6%80%81/Docker/" title="docker"><img src="https://s1.ax1x.com/2022/05/19/OHACxx.md.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="docker"/></a><div class="content"><a class="title" href="/2022/01/29/%E4%BA%92%E8%81%94%E7%BD%91%E7%94%9F%E6%80%81/Docker/" title="docker">docker</a><time datetime="2022-01-28T16:37:00.000Z" title="发表于 2022-01-29 00:37:00">2022-01-29</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By Sun Moon</div><div class="footer_custom_text"><a href="https://beian.miit.gov.cn/"  style="color:white" target="_blank">晋ICP备2022004590号-1</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js"></script><div class="js-pjax"></div><script src="https://widget.qweather.net/simple/static/js/he-simple-common.js?v=2.0"></script><script async src="/js/weather.js"></script><script src="https://myhkw.cn/player/js/jquery.min.js" type="text/javascript"></script><script src="https://myhkw.cn/api/player/1651412271121" id="myhk" key="1651412271121" m="1"></script><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="true" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-show-text.min.js" data-mobile="true" data-text="暴帅,暴富,健康,happy" data-fontsize="15px" data-random="true" async="async"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = ["title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>